//
//  GCDUtil.m
//  IOS_SST
//
//  Created by lfy on 16/4/28.
//  Copyright © 2016年 jiahua. All rights reserved.
//

#import "GCDUtil.h"
#import <arpa/inet.h>

@implementation GCDUtil

/**
 *  从给定的address获取ip地址
 *
 *  @param address address description
 *
 *  @return IP地址
 */
+(NSString *)getIPAddressFromAddress:(NSData *)address {
    
    Byte* addreBytes = (Byte *)[address bytes];
    char addrBuf[MAX(INET_ADDRSTRLEN,INET6_ADDRSTRLEN)];
    
    NSString *ipAddress;
    struct sockaddr_in *sockaddr = (struct sockaddr_in*)addreBytes;
    
    switch (sockaddr->sin_family)
    {
        case AF_INET://ip 4
            if(inet_ntop(AF_INET, &sockaddr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                ipAddress =[NSString stringWithUTF8String: addrBuf];
            }
            break;
        case AF_INET6: { //ip 6
            struct sockaddr_in6 *sockaddr = (struct sockaddr_in6*)addreBytes;
            if(inet_ntop(AF_INET6, &sockaddr->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                ipAddress =[NSString stringWithUTF8String: addrBuf];
                //对于IPv6要使用正则表达式提取字符串中的IP地址
                NSRange range = [ipAddress rangeOfString:@"((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)" options:NSRegularExpressionSearch];
                if(range.location != NSNotFound){
                    ipAddress = [ipAddress substringWithRange:range];
                }
                
            }
            break;
        }
    }
    return ipAddress;
}


//判断IP是否为广播
+(Boolean) isBroadCaseByIp:(NSString *)ip
{
    if (ip == nil)
        return  false;
    
    return [ip isEqualToString:@"255.255.255.255"];
}

+(Boolean) isBroadCaseByAddress:(NSData *)address
{
    if (address == nil)
        return false;
    
    return [GCDUtil isBroadCaseByIp: [GCDUtil getIPAddressFromAddress: address]];
}
@end
